
<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { showToast  } from 'vant'
  import { useAddress } from '@/store/address.ts'
  import { productDetailAPIRes, techDetailAPIRes, couponListAPIRes, placeOrderAPIRes, orderAddAPIRes } from '@/api'
  import dayjs from 'dayjs'
  import wx from 'weixin-js-sdk'

  const { query } = useRoute()
  const router = useRouter()
  const userAddress = useAddress()
  const productDetail = ref<any>({})
  const couponList = ref<any>([])
  const showList = ref(false)
  const formData = ref<any>({
    pid: Number(query.pid),
    aid: userAddress.id,
    cid: null,
    fareAmount: 0,
    discountAmount: 0,
    totalAmount: 0,
    remark: '',
    payType: 1,
    productName: '',
    userName: userAddress.name,
    techInfo: {
      id: null,
      openid: '',
      mobile: '',
      nickname: ''
    }
  })

  const getProductDetail = async () => {
    const { data } = await productDetailAPIRes({ id: query.pid })
    productDetail.value = data
    formData.value.productName = data.name
  }
  const getTechDetail = async () => {
    const { data } = await techDetailAPIRes({ id: query.tid })
    userAddress.techLocation = data.location
    formData.value.techInfo.id = data.id
    formData.value.techInfo.openid = data.openid
    formData.value.techInfo.mobile = data.mobile
    formData.value.techInfo.nickname = data.nickname
  }
  const getCouponList = async () => {
    const { data } = await couponListAPIRes({ type: 1 })
    // couponList.value = data.filter((item: any) => productDetail.value.price + userAddress.fare >= item.discount)
    couponList.value = data
  }
  const onCoupon = (item: any) => {
    formData.value.cid = item.id
    formData.value.discountAmount = item.price
    showList.value = false
  }
  // 提交订单
  const onSubmit = async() => {
    if (!formData.value.aid) {
      showToast('请选择服务地址')
      return
    }
    formData.value.fareAmount = userAddress.fare
    formData.value.totalAmount = Number((productDetail.value.price + userAddress.fare - formData.value.discountAmount).toFixed(2))
    const { data } = await placeOrderAPIRes({ totalAmount: formData.value.totalAmount, productName: formData.value.productName })
    wx.chooseWXPay({
      timestamp: data.data.timeStamp,
      nonceStr: data.data.nonceStr,
      package: data.data.package,
      signType: data.data.signType,
      paySign: data.data.paySign,
      success: async() => {
        const opt = JSON.parse(JSON.stringify(formData.value))
        opt.orderNo = data.orderNo
        await orderAddAPIRes(opt)
        showToast('下单成功')
        router.replace({ path: '/order' })
      },
      cancel: (err) => {
        console.log('err')
        console.log(err)
      },
      fail: (fa) => {
        console.log('fa')
        console.log(fa)
      }
    })
  }

  onMounted(() => {
    getProductDetail()
    getTechDetail()
    getCouponList()
  })
</script>

<template>
  <van-nav-bar safe-area-inset-top fixed placeholder left-arrow @click-left="router.back()" />
  <van-cell-group inset class="mb-2.5 mt-2.5">
    <van-cell center is-link to="/address">
      <template #icon>
        <van-icon name="location" size="23" color="#7C6186" class="mr-2.5" />
      </template>
      <template #title>
        <span class="mr-2 text-base font-bold">{{ userAddress.name || '请选择服务地址' }}</span>
        <span>{{ userAddress.phone }}</span>
      </template>
      <template v-if="userAddress.address" #label>
        <span class="text-sm text-[#333]">{{ userAddress.address }}</span>
      </template>
    </van-cell>
  </van-cell-group>
  <van-cell-group inset class="p-2.5 mb-2.5">
      <div class="flex items-center">
          <van-image
              radius="8"
              width="4rem"
              height="4rem"
              fit="cover"
              :src="productDetail.productImg"
          />
          <div class="ml-2.5 flex-1">
              <div class="flex items-center justify-between">
                  <span class="text-base font-bold text-[#232a24]">{{ productDetail.name }}</span>
                  <span class="text-base text-[#ff2404]">¥ {{ productDetail.price && (productDetail.price).toFixed(2) }}</span>
              </div>
              <div class="text-xs text-[#666]">服务时长：{{ productDetail.duration }}分钟</div>
              <div class="text-xs text-[#666]">服务技师：{{ formData.techInfo.nickname }}</div>
          </div>
      </div>
      <van-divider />
      <van-cell title="预计到达" center :border="false" class="p-0 py-1">
        <span class="text-[#333]">{{ dayjs().add(30, 'minute').format('YYYY-MM-DD HH:mm') }}</span>
      </van-cell>
      <van-cell title="出行方式" center :border="false" class="p-0 py-1">
        <span class="text-[#333]">打车</span>
      </van-cell>
  </van-cell-group>
  <van-cell-group inset class="p-2.5 mb-2.5">
      <van-cell title="往返车费" :border="false" class="p-0 py-1">
        <span class="text-[#ff2404]">¥ {{ userAddress.fare }}</span>
      </van-cell>
      <div class="p-2.5 bg-slate-100 rounded-lg text-xs text-[#888]">单程{{ userAddress.distance }}公里，单程起步价10元3公里，单程超出3公里后每公里2.5元</div>
      <van-cell is-link title="优惠劵" :border="false" class="p-0 py-1" @click="showList = true">
        <span class="text-[#ff2404]">{{ formData.discountAmount ? '-￥' + formData.discountAmount.toFixed(2) : couponList.length + '张可用' }}</span>
      </van-cell>
  </van-cell-group>
  <van-cell-group inset class="p-2.5 mb-2.5">
    <van-field
      v-model="formData.remark"
      rows="5"
      autosize
      label-align="top"
      type="textarea"
      maxlength="100"
      placeholder="请输入订单备注"
      show-word-limit
      class="p-0"
    >
      <template #label>
        <div class="flex items-center">
          <span>订单备注</span>
          <span class="text-[#999] text-xs">（选填）</span>
        </div>
      </template>
    </van-field>
</van-cell-group>
  <van-radio-group v-model="formData.payType" class="mb-2.5">
    <van-cell-group inset>
      <van-cell center clickable title="微信支付" @click="formData.payType = 1">
        <template #icon>
          <van-icon name="wechat-pay" color="#19c865" :size="20" class="mr-1" />
        </template>
        <template #right-icon>
          <van-radio :name="1" checked-color="#7C6186" />
        </template>
      </van-cell>
      <!-- <van-cell clickable @click="formData.payType = 2">
        <template #title>
          <span>账户余额</span>
          <span class="ml-1 text-xs text-[#999]">余额0元</span>
        </template>
        <template #icon>
          <van-icon name="wechat-pay" color="#19c865" :size="20" class="mr-1" />
        </template>
        <template #right-icon>
          <van-radio :name="2" checked-color="#7C6186" />
        </template>
      </van-cell> -->
    </van-cell-group>
  </van-radio-group>
  <van-submit-bar
      :price="(productDetail.price + userAddress.fare - formData.discountAmount) * 100"
      button-text="提交订单"
      label="实付款"
      button-color="#7C6186"
      text-align="left"
      placeholder
      @submit="onSubmit"
  />
  <!-- 优惠券列表 -->
  <van-popup
    v-model:show="showList"
    round
    closeable
    safe-area-inset-bottom
    position="bottom"
    :style="{ height: '70%', paddingTop: '4px' }"
  >
    <div v-if="couponList.length > 0" class="p-4">
      <div v-for="item in couponList" :key="item.id" class="h-[150px] p-2.5 coupon_bg bg-[length:100%_100%] bg-no-repeat mb-3" @click="onCoupon(item)">
        <div class="text-2xl italic font-bold leading-[30px] text-[#ea0000]">{{ item.name }}</div>
        <div class="flex items-center justify-between h-[100px] pl-4 coupon_bg2 bg-[length:100%_100%] bg-no-repeat">
          <div class="text-xl text-[#ea0000] drop-shadow-lg">¥<span class="font-bold text-4xl italic">{{ item.price }}</span></div>
          <div class="text-[#bf8e5e] text-sm leading-8">
            <div class="border-b border-dashed border-[#bf8e5e]">满{{ item.discount }}可使用</div>
            <div>有效期至{{ item.overdueAt }}</div>
          </div>
          <div class="px-5 text-[#ea0000] text-base">立即使用</div>
        </div>
      </div>
    </div>
    <van-empty v-else image-size="100" description="暂无优惠劵" />
  </van-popup>
</template>